import React,{
  forwardRef,
  useContext,
  useEffect,
  useImperativeHandle,
  useMemo,
  useState,
} from "react";
import routingService from "@/api/services/mes/routingService";
import processService from "@/api/services/mes/processService";
import { TableToolbar } from "@/components/grid/TableToolbar";
import { Button, Input, InputNumber, Select, Tooltip } from "antd";
import Table, { type ColumnsType } from "antd/es/table";
import { toast } from "sonner";
import type { MesRoutingProcess } from "./entity";
import useDictionary from "@/hooks/system/useDictionary";
import type { MesProcess } from "../process/entity";

import { HolderOutlined } from "@ant-design/icons";
import type { DragEndEvent } from "@dnd-kit/core";
import { DndContext } from "@dnd-kit/core";
import type { SyntheticListenerMap } from "@dnd-kit/core/dist/hooks/utilities";
import { restrictToVerticalAxis } from "@dnd-kit/modifiers";
import {
  SortableContext,
  arrayMove,
  useSortable,
  verticalListSortingStrategy,
} from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";

interface MesRoutingProcessProps {
  parentId?: React.Key;
}

export interface MesRoutingProcessHandles {
  getAddList: () => MesRoutingProcess[];
  getUpdateList: () => MesRoutingProcess[];
  getDeleteIds: () => React.Key[];
}

interface RowContextProps {
  setActivatorNodeRef?: (element: HTMLElement | null) => void;
  listeners?: SyntheticListenerMap;
}

interface RowProps extends React.HTMLAttributes<HTMLTableRowElement> {
  "data-row-key": string;
}

const RowContext = React.createContext<RowContextProps>({});
const DragHandle: React.FC = () => {
  const { setActivatorNodeRef, listeners } = useContext(RowContext);
  return (
    <Button
      type="text"
      size="small"
      icon={<HolderOutlined />}
      style={{ cursor: "move" }}
      ref={setActivatorNodeRef}
      {...listeners}
    />
  );
};
const Row: React.FC<RowProps> = (props) => {
  const {
    attributes,
    listeners,
    setNodeRef,
    setActivatorNodeRef,
    transform,
    transition,
    isDragging,
  } = useSortable({ id: props["data-row-key"] });

  const style: React.CSSProperties = {
    ...props.style,
    transform: CSS.Translate.toString(transform),
    transition,
    ...(isDragging ? { position: "relative", zIndex: 9999 } : {}),
  };

  const contextValue = useMemo<RowContextProps>(
    () => ({ setActivatorNodeRef, listeners }),
    [setActivatorNodeRef, listeners]
  );

  return (
    <RowContext.Provider value={contextValue}>
      <tr {...props} ref={setNodeRef} style={style} {...attributes} />
    </RowContext.Provider>
  );
};

//与下工序关系
const linkHelp = `S-to-S：当前工序开始生产，下一道工序才可开始生产
F-to-F：当前工序结束生产，下一道工序才可结束生产
S-to-F：当前工序开始生产，下一道工序才可结束生产
F-to-S：当前工序结束生产，下一道工序才可开始生产
`;
//是否关键工序
const keyFlagHelp = `是：整个工单的生产进度将根据当前工序的生产报工数量进行更新
每个工艺流程只能有一个关键工序`;
//是否检验
const isCheckHelp = `是：当前工序报工时需要进行质检确认
质检合格数量作为最终生产数量`;                    


const MesRoutingProcessPage = forwardRef<
  MesRoutingProcessHandles,
  MesRoutingProcessProps
>(({ parentId }, ref) => {
  const [loading, setLoading] = useState(false);
  const [processList, setProcessList] = useState<MesProcess[]>([]);
  const [list, setList] = useState<MesRoutingProcess[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  // 添加一个状态来跟踪临时ID
  const [tempIds, setTempIds] = useState<React.Key[]>([]);
  const [addList, setAddList] = useState<MesRoutingProcess[]>([]);
  const [updateList, setUpdateList] = useState<MesRoutingProcess[]>([]);
  const [deleteIds, setDeleteIds] = useState<React.Key[]>([]);

  useImperativeHandle(
    ref,
    () => ({
      getAddList: () => addList,
      getUpdateList: () => updateList,
      getDeleteIds: () => deleteIds,
    }),
    [addList, updateList, deleteIds]
  );

  useEffect(() => {
    const newAddList = list.filter(
      (item) => item.id && tempIds.includes(item.id)
    );
    setAddList(newAddList);
    const updateList = list.filter(
      (item) => item.id && !tempIds.includes(item.id)
    );
    setUpdateList(updateList);
  }, [list]);

  const [tableSize, setTableSize] = useState<"large" | "middle" | "small">(
    "middle"
  );

  //动态设置表格高度
  const [tableScrollY, setTableScrollY] = useState(0);
  const PAGE_OFFSET_HEIGHT = 403;
  const updateTableHeight = () => {
    const newHeight = window.innerHeight - PAGE_OFFSET_HEIGHT;
    setTableScrollY(newHeight > 200 ? newHeight : 200); // 保证最小高度
  };

  // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
  useEffect(() => {
    updateTableHeight(); // 初始化
    window.addEventListener("resize", updateTableHeight);
    return () => window.removeEventListener("resize", updateTableHeight);
  }, []);

  const linkTypeOptions = useDictionary("process_link_type");
  const keyFlagOptions = useDictionary("system_true_false");
  const isCheckOptions = useDictionary("system_true_false");


  useEffect(() => {
    getProcessList(); // 初始化时获取工序列表
  }, []);

  //表格列定义
  const columns: ColumnsType<MesRoutingProcess> = useMemo(() => [
    { key: "sort",dataIndex:"sort", align: "center", width: 32, render: () => <DragHandle /> },
    {
      title: "序号",
      width: 50,
      align: "center",
      key: "orderNum",
      dataIndex: "orderNum",
    },
    {
      title: "工序",
      width: 120,
      key: "processId",
      dataIndex: "processId",
      render: (text, record) => (
        <Select
          value={text}
          options={processList.map((item) => ({
            value: item.id,
            label: item.processName,
          }))}
          onChange={(value) => handleFieldChange(record.id, "processId", value)}
          style={{ width: "100%" }}
        />
      ),
    },
    {
      title: (
        <Tooltip 
            title={
                <div style={{maxWidth: 500, whiteSpace:"pre-wrap"}} slot="content">
                    {linkHelp}
                </div>
            }
            overlayStyle={{ maxWidth: 500}}
        >
            <span>与下一道工序关系</span>
        </Tooltip>
      ),
      width: 120,
      key: "linkType",
      dataIndex: "linkType",
      render: (text, record) => (
        <Select
          value={text}
          onChange={(value) => handleFieldChange(record.id, "linkType", value)}
          options={linkTypeOptions}
          allowClear
          style={{ width: "100%" }}
        />
      ),
    },
    {
      title: "准备时间",
      width: 120,
      key: "defaultPreTime",
      dataIndex: "defaultPreTime",
      render: (text, record) => (
        <InputNumber
          value={text}
          onChange={(value) =>
            handleFieldChange(record.id, "defaultPreTime", value)
          }
          style={{ width: "100%" }}
        />
      ),
    },
    {
      title: "等待时间",
      width: 120,
      key: "defaultSufTime",
      dataIndex: "defaultSufTime",
      render: (text, record) => (
        <InputNumber
          value={text}
          onChange={(value) =>
            handleFieldChange(record.id, "defaultSufTime", value)
          }
          style={{ width: "100%" }}
        />
      ),
    },
    {
      title: (
        <Tooltip 
            title={
                <div style={{maxWidth: 500, whiteSpace:"pre-wrap"}} slot="content">
                    {keyFlagHelp}
                </div>
            }
            overlayStyle={{ maxWidth: 500}}
        >
            <span>关键工序</span>
        </Tooltip>
      ),
      width: 120,
      key: "keyFlag",
      dataIndex: "keyFlag",
      render: (text, record) => (
        <Select
          value={text}
          onChange={(value) => handleFieldChange(record.id, "keyFlag", value)}
          options={keyFlagOptions}
          allowClear
          style={{ width: "100%" }}
        />
      ),
    },
    {
      title: (
        <Tooltip 
            title={
                <div style={{maxWidth: 500, whiteSpace:"pre-wrap"}} slot="content">
                    {isCheckHelp}
                </div>
            }
            overlayStyle={{ maxWidth: 500}}
        >
            <span>是否检验</span>
        </Tooltip>
      ),
      width: 120,
      key: "isCheck",
      dataIndex: "isCheck",
      render: (text, record) => (
        <Select
          value={text}
          onChange={(value) => handleFieldChange(record.id, "isCheck", value)}
          options={isCheckOptions}
          allowClear
          style={{ width: "100%" }}
        />
      ),
    },
    {
      title: "备注",
      width: 120,
      key: "remark",
      dataIndex: "remark",
      render: (text, record) => (
        <Input
          value={text}
          onChange={(e) =>
            handleFieldChange(record.id, "remark", e.target.value)
          }
        />
      ),
    },
  ], [processList, linkTypeOptions, keyFlagOptions, isCheckOptions]); ;

  const onDragEnd = ({ active, over }: DragEndEvent) => {
    if (active.id !== over?.id) {
      setList((prevState) => {
        const activeIndex = prevState.findIndex(
          (record) => record.id === active?.id
        );
        const overIndex = prevState.findIndex(
          (record) => record.id === over?.id
        );
        // 排序后的新数组
        const newList = arrayMove(prevState, activeIndex, overIndex);

        // 重新设置 partIndex
        return newList.map((item, index) => ({
          ...item,
          orderNum: index + 1, // 从 1 开始编号
        }));
      });
    }
  };

  const [selectedValues, setSelectedValues] = useState<string[]>(() =>
    columns
      .filter((col) => col.key !== "operation")
      .map((col) => (col.key ? String(col.key) : ""))
  );

  // 处理字段变更
  const handleFieldChange = (id: string, field: string, value: any) => {
    let inputValue: any = null;
    // 如果是checkbox的值，将布尔值转换为数字值（true为1，false为0）
    if (typeof value === "boolean") {
      inputValue = value ? 1 : 0;
    } else if (value instanceof Date) {
      // 处理日期格式
      inputValue = dayjs(value).format("YYYY-MM-DD");
    } else {
      inputValue = value;
    }

    setList((prevData) =>
      prevData.map((item) =>
        item.id === id ? { ...item, [field]: inputValue } : item
      )
    );
  };

  // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
  const filteredColumns = useMemo(() => {
    return [
      ...columns.filter(
        (col) =>
          selectedValues.includes(String(col.key)) || col.key === "operation"
      ),
    ].sort((a, b) => {
      const originalIndex = columns.findIndex((c) => c.key === a.key);
      const targetIndex = columns.findIndex((c) => c.key === b.key);
      return originalIndex - targetIndex;
    });
  }, [selectedValues, processList, linkTypeOptions, keyFlagOptions, isCheckOptions]);

  //加载表格数据
  const fetchList = () => {
    if (!parentId) return;

    setLoading(true);
    routingService
      .getProcessList(parentId)
      .then((res) => {
        setList(res);
      })
      .catch((error) => {
        console.log(error);
        toast.error("获取数据失败！", error);
      })
      .finally(() => {
        setLoading(false);
      });
  };

  //获取工序列表
  const getProcessList = async () => {
    await processService.list()
      .then((res) => {
        setProcessList(Array.isArray(res) ? res : res.data || []);
      })
      .catch((error) => {
        console.log(error);
        toast.error("获取工序列表失败！", error);
      });
  };

  // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
  useEffect(() => {
    if (parentId) {
      fetchList();
    } else {
      // 初始化时清空状态
      setList([]);
      setSelectedRowKeys([]);
      setTempIds([]);
      setAddList([]);
      setUpdateList([]);
      setDeleteIds([]);
    }
  }, [parentId]);

  //检验是否输入值
  const validatePartsBeforeAdd = (): boolean => {
    for (const detail of list) {
        if (!detail.processId) {
            toast.error(`（序号 ${detail.orderNum}）工序不能为空，请选择工序！`);
            return false;
        }
    }
    return true;
  };

  const handleAdd = () => {
    if (!validatePartsBeforeAdd()) {
      return; // 校验未通过，不执行新增
    }

    const newId = Date.now().toString();
    const newDetail: MesRoutingProcess = {
      id: newId,
      routingId: parentId,
      keyFlag: "0",
      isCheck: "0",
      orderNum: list.length + 1, // 新增的内容顺序号为当前列表长度加1
    };

    // 添加到临时ID列表
    setTempIds((prev) => [...prev, newId]);
    setList((prev) => [...prev, newDetail]);
  };

  // 在删除方法中修改判断逻辑
  const handleDelete = () => {
    // 如果没有选中行，直接返回
    if (selectedRowKeys.length === 0) {
      return;
    }

    // 更新删除ID列表
    const newDeleteIds = [...deleteIds];

    // 将已有ID但不在deleteIds中的ID添加到deleteIds
    for (const key of selectedRowKeys) {
      const item = list.find((item) => item.id === key);
      if (item?.id && !tempIds.includes(item.id)) {
        // 如果不在临时ID列表中，则添加到删除列表
        if (!newDeleteIds.includes(item.id)) {
          newDeleteIds.push(item.id);
        }
      }
    }

    // 更新deleteIds状态
    setDeleteIds(newDeleteIds);

    // 从列表中移除选中的行，并重新排序 orderNum
    setList((prevList) => {
      const filtered = prevList.filter(
        (item) => !selectedRowKeys.includes(item.id)
      );
      // 重新排序 orderNum
      return filtered.map((item, idx) => ({
        ...item,
        orderNum: idx + 1,
      }));
    });

    // 从tempIds中移除被删除的临时ID
    setTempIds((prevTempIds) =>
      prevTempIds.filter((id) => !selectedRowKeys.includes(id))
    );
    // 清空选中状态
    setSelectedRowKeys([]);
  };

  return (
    <>
      <div className="flex justify-between mb-4">
        <div className="flex gap-2">
          <Button type="primary" onClick={handleAdd}>
            新增
          </Button>
          <Button
            danger
            disabled={selectedRowKeys.length === 0}
            onClick={handleDelete}
          >
            删除
          </Button>
        </div>
        <TableToolbar
          onRefresh={() => fetchList()}
          onSizeChange={setTableSize}
          columns={columns}
          selectedValues={selectedValues}
          onColumnChange={setSelectedValues}
        />
      </div>
      <DndContext modifiers={[restrictToVerticalAxis]} onDragEnd={onDragEnd}>
        <SortableContext
          items={list.map((i) => i.id)}
          strategy={verticalListSortingStrategy}
        >
          <Table
            rowKey="id"
            size={tableSize}
            scroll={{ x: "max-content", y: tableScrollY }}
            components={{ body: { row: Row } }}
            loading={loading}
            pagination={false}
            columns={filteredColumns}
            dataSource={list}
            rowSelection={{
              type: "checkbox",
              selectedRowKeys: selectedRowKeys,
              onChange: (selectedKeys) => {
                setSelectedRowKeys(selectedKeys as React.Key[]);
              },
            }}
          />
        </SortableContext>
      </DndContext>
    </>
  );
});

export default MesRoutingProcessPage;
